package com.gyh.system.sys.web;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import com.gyh.system.common.persistence.BaseController;
import com.gyh.system.common.utils.Global;
import com.gyh.system.common.utils.R;
import com.gyh.system.common.validator.ValidatorUtils;
import com.gyh.system.sys.entity.User;
import com.gyh.system.sys.service.ShiroService;
import com.gyh.system.sys.service.SystemService;
import com.gyh.system.sys.utils.UserModel;

/**
 * 
 * @author 作者 gyh
 * @version 创建时间：2018年7月11日 下午8:28:15
 */
@RestController
public class LoginController extends BaseController{

	@Autowired
	private SystemService systemService;
	
	@Autowired
	private ShiroService shiroService;
	
	
	/**
	 * 登入
	 */
	@PostMapping("login")
	public R login(@RequestBody UserModel userModel) {
		String username = userModel.getUsername();
		String password = userModel.getPassword();
		//String captcha = userModel.getCaptcha();
		ValidatorUtils.isBlank(username, "用户名不能为空");
		ValidatorUtils.isBlank(password, "密码不能为空");
		//ValidatorUtils.isBlank(captcha, "验证码不能为空");
		
		//获取用户
		User user = systemService.getUserByUsername(username);
		
		//账号不存在或密码错误
		if ( user == null || !systemService.validatePassword(password,user.getPassword())) {
			return R.error("用户名或密码不正确");
		}
		
		//账号被锁
		if ("0".equals(user.getLoginFlag())) {
			return R.error("账号已被锁");
		}
		
		//判断是否是debug模式
		if (Global.isDebugMode()) {
			if (user.getId() == 1) {
				return R.ok().put("token", 1);
			} else {
				return systemService.createToken(user.getId());
			}
		} else {
			return systemService.createToken(user.getId());
		}
	}
	
	
}
